package com.bytecub.simulate.device.instance;

import com.bytecub.common.domain.DataResult;
import com.bytecub.common.domain.dto.PageReqDto;
import com.bytecub.common.domain.dto.PageResDto;
import com.bytecub.common.domain.dto.request.DevQueryReqDto;
import com.bytecub.common.domain.dto.request.prop.TemplateReqDto;
import com.bytecub.common.domain.dto.response.device.DevicePageResDto;
import com.bytecub.common.domain.dto.response.prop.TemplateResDto;
import com.bytecub.common.enums.BCErrorEnum;
import com.bytecub.common.metadata.ProductFuncTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 *  * ByteCub.cn.
 *  * Copyright (c) 2020-2021 All Rights Reserved.
 *  * 物模型demo数据
 *  * @author bytecub@163.com songbin
 *  * @version Id: DeviceDemoDataService.java, v 0.1 2021-02-20  Exp $$
 *  
 */
@Service
@Slf4j
public class DeviceDemoDataService {
    @Value("${bytecub.device.http.demo-url}")
    String demoUrl;
    @Autowired
    AuthHeaderService authHeaderService;

    /**
     * 初始化模版数据
     * 
     * @param productCode String
     * @param typeEnum    ProductFuncTypeEnum
     * @return
     */
    public TemplateResDto initProductDemo(String productCode, ProductFuncTypeEnum typeEnum) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            MultiValueMap<String, String> headers = authHeaderService.buildHeader();
            TemplateReqDto request = new TemplateReqDto();
            request.setFuncType(typeEnum.getType());
            request.setProductCode(productCode);
            HttpEntity httpEntity = new HttpEntity<TemplateReqDto>(request, headers);
            ResponseEntity<DataResult<TemplateResDto>> responseEntity = restTemplate
                    .exchange(demoUrl, HttpMethod.POST, httpEntity,
                            new ParameterizedTypeReference<DataResult<TemplateResDto>>() {
                            });
            log.info("{}", responseEntity);
            if (responseEntity.getBody().getCode() != BCErrorEnum.SUCCESS.getCode()) {
                log.warn("启动HTTP模拟器失败{}", responseEntity);
                System.exit(-1);
            }
            return responseEntity.getBody().getData();
        } catch (Exception e) {
            log.warn("初始化数据异常", e);
            return null;
        }
    }

}
